package tech.aistar.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tech.aistar.Code.IdCardCheck;
import tech.aistar.Code.PhoneMessage;
import tech.aistar.entity.*;
import tech.aistar.service.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Controller
@RequestMapping("/Tenant")
public class TenantCentre {
    @Autowired
    private ITenantService tenantService;
    @Autowired
    private IRegisterService registerService;
    @Autowired
    private IMessageService messageService;
    @Autowired
    private ISeeRoomTrendService seeRoomTrendService;
    @Autowired
    private IImageService iImageService;
    @Autowired
    private IHouseService iHouseService;
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/info/{tenantId}")
    public String select(HttpServletRequest request, @PathVariable("tenantId") Integer tenantId) {
//        String tenantId = request.getParameter("tenantId");
        Tenant tenant = tenantService.selectById(Integer.valueOf(tenantId));
        request.setAttribute("tenant", tenant);
        Register register = registerService.selectById(tenant.getRegisterId());
        request.setAttribute("register", register);

        List<Message> messageStates = messageService.selectByState(register.getId());
        request.setAttribute("messageSize", messageStates.size());

        List<SeeRoomTrend> seeRoomTrends=seeRoomTrendService.selectThree();
        int i=0;
        for (SeeRoomTrend seeRoomTrend : seeRoomTrends) {
            i++;
           request.setAttribute("image"+i, iImageService.selectOneByHouseId(seeRoomTrend.getHouseId()));
           request.setAttribute("house"+i,iHouseService.selectByhouseId(seeRoomTrend.getHouseId()));
        }
        return "/personal_homepage/tenant/info";
    }

    @PostMapping("/changepwd")
    public @ResponseBody
    Result updatepwd(Integer id, String password) {
        int count = registerService.updateById(id, password);

        if (count == 1) {
            return new Result("200", "修改成功", registerService.selectById(id));
        } else {
            return new Result("500", "修改失败");
        }
    }

    @PostMapping("/GetCode")
    public @ResponseBody
    Result getcode(HttpServletRequest request, String phone){
//        final HttpSession httpSession = request.getSession();
//        httpSession.removeAttribute("checkCode");
//        httpSession.removeAttribute("checkPhone");
        redisTemplate.delete("checkCode1");
        redisTemplate.delete("checkPhone1");
        String checkCode = PhoneMessage.getPhonemsg(phone);
        if (checkCode != "true") {
//            System.out.println(checkCode);
//            httpSession.setAttribute("checkCode", checkCode);
//            httpSession.setAttribute("checkPhone", phone);
            redisTemplate.opsForValue().set("checkCode1", checkCode, 5, TimeUnit.MINUTES);
            redisTemplate.opsForValue().set("checkPhone1", phone, 5, TimeUnit.MINUTES);
//            final Timer timer = new Timer();
//            timer.schedule(new TimerTask() {
//                @Override
//                public void run() {
//                    httpSession.removeAttribute("checkCode");
//                    httpSession.removeAttribute("checkPhone");
//                    System.out.println("checkCode删除成功");
//                    timer.cancel();
//                }
//            }, 1000 * 60 * 5);
            return new Result("200", "获取成功");
        } else {
            return new Result("500", "获取失败");
        }

    }


    @PostMapping("/changephone")
    public @ResponseBody
    Result updatephone(HttpServletRequest request, String phone, Integer id, String code) {
//        String checkCode = (String) request.getSession().getAttribute("checkCode");
//        String checkPhone = (String) request.getSession().getAttribute("checkPhone");
        String checkCode = (String) redisTemplate.opsForValue().get("checkCode1");
        String checkPhone = (String) redisTemplate.opsForValue().get("checkPhone1");
        if (code.equals(checkCode) && phone.equals(checkPhone)) {
            int count = tenantService.updateById(phone, id);
//            request.getSession().removeAttribute("checkCode");
//            request.getSession().removeAttribute("checkPhone");
            redisTemplate.delete("checkCode1");
            redisTemplate.delete("checkPhone1");
            Result result = new Result("200", "修改成功", tenantService.selectById(id));
            return result;
        } else {
            return new Result("500", "验证码错误");
        }
    }


//    @PostMapping("/changename")
//    public @ResponseBody
//    Result updatename(String name, Integer id) {
//
//        int count = tenantService.updateNameById(name, id);
//
//        if (count == 1) {
//            return new Result("200", "修改成功", tenantService.selectById(id));
//        } else {
//            return new Result("500", "修改失败");
//        }
//    }


//    @PostMapping("/changegender")
//    public @ResponseBody
//    Result updategender(String gender, Integer id) {
//
//        int count = tenantService.updategenderById(gender, id);
//
//        if (count == 1) {
//            return new Result("200", "修改成功", tenantService.selectById(id));
//        } else {
//            return new Result("500", "修改失败");
//        }
//    }


    @PostMapping("/insertIdentity")
    public @ResponseBody
    Result insertIdentity(String identity, Integer id, String name) {
        JSONObject jsonObject = IdCardCheck.IdCardCheck(name, identity);
        if ("true".equals(jsonObject.getString("isok"))) {
//            System.out.println(jsonObject.getJSONObject("IdCardInfor").getString("sex"));
            String gender = "";
            if ("男".equals(jsonObject.getJSONObject("IdCardInfor").getString("sex"))) {
                gender = "true";
            } else {
                gender = "false";
            }
            int count = tenantService.updateIdentityById(identity, name, gender, id);
            if (count == 1) {
                return new Result("200", "认证成功", jsonObject.getJSONObject("IdCardInfor").getString("sex"));
            } else {
                return new Result("300", "认证失败");
            }
        } else {
            return new Result("500", "认证失败");
        }


//        int count = tenantService.updateIdentityById(identity, id);
//
//        if(count==1){
//            return new Result("200","修改成功",tenantService.selectById(id));
//        }else{
//            return new Result("500","修改失败");
//        }
    }


    @GetMapping("/Pic")
    public String Pic(HttpServletRequest request) {
        return "/personal_homepage/Pic";
    }


    @PostMapping("/lay")
    public @ResponseBody
    Result uploads(HttpServletRequest req, @RequestParam("file") MultipartFile file) {
        //重新进行命名
        String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
//        String path = req.getServletContext().getRealPath("/img/");

        //构建File实例
        File f = new File("D:/nginx/html/img/" + fileName);

//        System.out.println(f);
        try {
            file.transferTo(f);
        } catch (IOException e) {
            e.printStackTrace();
        }
        req.getSession().setAttribute("fileName", fileName);

        return new Result("200", "文件上传成功!", fileName);
    }


    @PostMapping("/changepic")
    public @ResponseBody
    Result updatePic(HttpServletRequest req, Integer tenantId) {
        String photograph = (String) req.getSession().getAttribute("fileName");
        req.getSession().removeAttribute("fileName");
        Tenant tenant = tenantService.selectById(tenantId);
        int count = tenantService.updatephotographById(photograph, tenantId);
        if (count == 1) {
            if (!tenant.getPhotograph().equals("h2.png")) {
                new File("D:/nginx/html/img/" + tenant.getPhotograph()).delete();
            }
            return new Result("200", "修改成功", photograph);
        } else {
            return new Result("500", "修改失败");
        }
    }


    @PostMapping("/delpic")
    public @ResponseBody
    Result delPic(HttpServletRequest req, String photograph) {
        new File("D:/nginx/html/img/" + photograph).delete();
        return new Result("200", "删除成功");
    }


}


